{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "ae1f50ec",
   "metadata": {},
   "source": [
    "<a href=\"https://colab.research.google.com/github/microsoft/FLAML/blob/main/notebook/autogen_agentchat_function_call.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "9a71fa36",
   "metadata": {},
   "source": [
    "# Auto Generated Agent Chat: Task Solving with Provided Tools as Functions\n",
    "\n",
    "`flaml.autogen` offers conversable agents powered by LLM, tool or human, which can be used to perform tasks collectively via automated chat. This framwork allows tool use and human participance through multi-agent conversation. Please find documentation about this feature [here](https://microsoft.github.io/autogen/docs/Use-Cases/agent_chat).\n",
    "\n",
    "In this notebook, we demonstrate how to use `AssistantAgent` and `UserProxyAgent` to make function calls with the new feature of OpenAI models (in model version 0613). A specified prompt and function configs need to be passed to `AssistantAgent` to initialize the agent. The corresponding functions need to be passed to `UserProxyAgent`, which will be responsible for executing any function calls made by `AssistantAgent`. Besides this requirement of matching descriptions with functions, we recommend checking the system message in the `AssistantAgent` to make sure the instructions align with the function call descriptions.\n",
    "\n",
    "## Requirements\n",
    "\n",
    "FLAML requires `Python>=3.8`. To run this notebook example, please install flaml with the [mathchat] option since we will import functions from `MathUserProxyAgent`:\n",
    "```bash\n",
    "pip install flaml[mathchat]\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "2b803c17",
   "metadata": {},
   "outputs": [],
   "source": [
    "# %pip install flaml[mathchat]~=2.0.0"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "5ebd2397",
   "metadata": {},
   "source": [
    "## Set your API Endpoint\n",
    "\n",
    "The [`config_list_from_models`](https://microsoft.github.io/FLAML/docs/reference/autogen/oai/openai_utils#config_list_from_models) function tries to create a list of configurations using Azure OpenAI endpoints and OpenAI endpoints for the provided list of models. It assumes the api keys and api bases are stored in the corresponding environment variables or local txt files:\n",
    "\n",
    "- OpenAI API key: os.environ[\"OPENAI_API_KEY\"] or `openai_api_key_file=\"key_openai.txt\"`.\n",
    "- Azure OpenAI API key: os.environ[\"AZURE_OPENAI_API_KEY\"] or `aoai_api_key_file=\"key_aoai.txt\"`. Multiple keys can be stored, one per line.\n",
    "- Azure OpenAI API base: os.environ[\"AZURE_OPENAI_API_BASE\"] or `aoai_api_base_file=\"base_aoai.txt\"`. Multiple bases can be stored, one per line.\n",
    "\n",
    "It's OK to have only the OpenAI API key, or only the Azure OpenAI API key + base.\n",
    "If you open this notebook in google colab, you can upload your files by click the file icon on the left panel and then choose \"upload file\" icon.\n",
    "\n",
    "The following code excludes Azure OpenAI endpoints from the config list because they don't support functions yet. Remove the `exclude` argument after they do."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "dca301a4",
   "metadata": {},
   "outputs": [],
   "source": [
    "from flaml import autogen\n",
    "\n",
    "config_list = autogen.config_list_from_models(model_list=[\"gpt-4\", \"gpt-3.5-turbo\", \"gpt-3.5-turbo-16k\"], exclude=\"aoai\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "92fde41f",
   "metadata": {},
   "source": [
    "The config list looks like the following:\n",
    "```python\n",
    "config_list = [\n",
    "    {\n",
    "        'model': 'gpt-4',\n",
    "        'api_key': '<your OpenAI API key here>',\n",
    "    },  # OpenAI API endpoint for gpt-4\n",
    "    {\n",
    "        'model': 'gpt-3.5-turbo',\n",
    "        'api_key': '<your OpenAI API key here>',\n",
    "    },  # OpenAI API endpoint for gpt-3.5-turbo\n",
    "    {\n",
    "        'model': 'gpt-3.5-turbo-16k',\n",
    "        'api_key': '<your OpenAI API key here>',\n",
    "    },  # OpenAI API endpoint for gpt-3.5-turbo-16k\n",
    "]\n",
    "```\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "2b9526e7",
   "metadata": {},
   "source": [
    "## Making Function Calls\n",
    "\n",
    "In this example, we demonstrate function call execution with `AssistantAgent` and `UserProxyAgent`. With the default system prompt of `AssistantAgent`, we allow the LLM assistant to perform tasks with code, and the `UserProxyAgent` would extract code blocks from the LLM response and execute them. With the new \"function_call\" feature, we define functions and specify the description of the function in the OpenAI config for the `AssistantAgent`. Then we register the functions in `UserProxyAgent`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "9fb85afb",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33muser_proxy\u001b[0m (to chatbot):\n",
      "\n",
      "Draw two agents chatting with each other with an example dialog. Don't add plt.show().\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mchatbot\u001b[0m (to user_proxy):\n",
      "\n",
      "\u001b[32m***** Suggested function Call: python *****\u001b[0m\n",
      "Arguments: \n",
      "{\n",
      "  \"cell\": \"\n",
      "import matplotlib.pyplot as plt\n",
      "import matplotlib.patches as mpatches\n",
      "\n",
      "# Define basic parameters\n",
      "face_color = '#FFDDC1'\n",
      "plt.figure(figsize=(10, 2))\n",
      "\n",
      "# Agent 1\n",
      "agent1 = mpatches.FancyBboxPatch((0.02, 0.4), 0.2, 0.6, boxstyle=mpatches.BoxStyle(\\\"Round\\\", pad=0.02))\n",
      "plt.gca().add_artist(agent1)\n",
      "plt.gca().text(0.12, 0.7, 'Agent 1', ha='center', va='center', fontsize=12, color='blue')\n",
      "\n",
      "# Agent 2\n",
      "agent2 = mpatches.FancyBboxPatch((0.45, 0.4), 0.2, 0.6, boxstyle=mpatches.BoxStyle(\\\"Round\\\", pad=0.02))\n",
      "plt.gca().add_artist(agent2)\n",
      "plt.gca().text(0.55, 0.7, 'Agent 2', ha='center', va='center', fontsize=12, color='red')\n",
      "\n",
      "# Dialog\n",
      "plt.gca().text(0.12, 0.35, '\\\"Hello, how are you?\\\"', ha='center', va='center', fontsize=10)\n",
      "plt.gca().text(0.55, 0.15, '\\\"I\\'m fine, thank you!\\\"', ha='center', va='center', fontsize=10)\n",
      "\n",
      "# Descriptions\n",
      "plt.gca().text(0.12, 0.15, 'Greeting', ha='center', va='center', fontsize=10)\n",
      "plt.gca().text(0.55, 0.35, 'Response', ha='center', va='center', fontsize=10)\n",
      "\n",
      "plt.axis('off')\n",
      "\"\n",
      "}\n",
      "\u001b[32m*******************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33muser_proxy\u001b[0m (to chatbot):\n",
      "\n",
      "\u001b[32m***** Response from calling function \"python\" *****\u001b[0m\n",
      "Error: Invalid \\escape: line 1 column 785 (char 784)\n",
      " You argument should follow json format.\n",
      "\u001b[32m***************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mchatbot\u001b[0m (to user_proxy):\n",
      "\n",
      "\u001b[32m***** Suggested function Call: python *****\u001b[0m\n",
      "Arguments: \n",
      "{\n",
      "  \"cell\": \"import matplotlib.pyplot as plt\\nimport matplotlib.patches as mpatches\\n\\n# Define basic parameters\\nface_color = '#FFDDC1'\\nplt.figure(figsize=(10, 2))\\n\\n# Agent 1\\nagent1 = mpatches.FancyBboxPatch((0.02, 0.4), 0.2, 0.6, boxstyle=mpatches.BoxStyle('Round', pad=0.02))\\nplt.gca().add_artist(agent1)\\nplt.gca().text(0.12, 0.7, 'Agent 1', ha='center', va='center', fontsize=12, color='blue')\\n\\n# Agent 2\\nagent2 = mpatches.FancyBboxPatch((0.45, 0.4), 0.2, 0.6, boxstyle=mpatches.BoxStyle('Round', pad=0.02))\\nplt.gca().add_artist(agent2)\\nplt.gca().text(0.55, 0.7, 'Agent 2', ha='center', va='center', fontsize=12, color='red')\\n\\n# Dialog\\nplt.gca().text(0.12, 0.35, '\\\"Hello, how are you?\\\"', ha='center', va='center', fontsize=10)\\nplt.gca().text(0.55, 0.15, '\\\"I\\\\'m fine, thank you!\\\"', ha='center', va='center', fontsize=10)\\n\\n# Descriptions\\nplt.gca().text(0.12, 0.15, 'Greeting', ha='center', va='center', fontsize=10)\\nplt.gca().text(0.55, 0.35, 'Response', ha='center', va='center', fontsize=10)\\n\\nplt.axis('off')\"\n",
      "}\n",
      "\u001b[32m*******************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[35m\n",
      ">>>>>>>> EXECUTING FUNCTION python...\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "(0.0, 1.0, 0.0, 1.0)"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAxoAAACuCAYAAACx83usAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjcuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8pXeV/AAAACXBIWXMAAA9hAAAPYQGoP6dpAAAsEElEQVR4nO3deXxM5/4H8M/MZJ3JTppEEomIRGyxRIu0xBLUmlZV0Sa20lJFUbR+DaVq6Y3lVl3u1UiprS6lTdTSK2goGklEVksESQiRbbJn5vn9kZoasQyOxvJ5v155vZwzz3nO9wyek8+c85yRCSEEiIiIiIiIJCSv6wKIiIiIiOjZw6BBRERERESSY9AgIiIiIiLJMWgQEREREZHkGDSIiIiIiEhyDBpERERERCQ5Bg0iIiIiIpIcgwYREREREUmOQYOIiIiIiCRnZGhDpeeLeOGN0MdZC1Gdyt02Fz2aOWLXrl11XQo95cLCwjDjk/+D8+StdV0K0WNTdHw7Ko5vRYm6uK5LIaInlOFXNGSyx1gG0ROA/8ZJSvznRM88/iMnonvjrVNERERERCQ5Bg0iIiIiIpIcgwYREREREUmOQYOIiIiIiCTHoEFERERERJJj0CAiIiIiIskxaBARERERkeQYNIiIiIiISHIMGkREREREJDkGDSIiIiIikhyDBhERERERSY5Bg4iIiIiIJMegQUREREREkmPQICIiIiIiyTFoEBERERGR5Bg0iIiIiIhIcgwaREREREQkOQYNIiIiIiKSHIMGERERERFJjkGDiIiIiIgkx6BBRERER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IiIqK7eirnaPwdmjdvjlOnThl8X+/zYPHixWjatCkcHR0xa9asui6HiIiIiJ5gvHWKiIiIiIgkx4/riYiIiIhIcgwaREREREQkOQYNIiIiIiKSHIMGERERERFJjkGDiIiIiIgkx6BBRERERESSY9AgIiIiIiLJMWgQEREREZHkGDSIiIiIiEhyDBpERERERCQ5Bg0iIiIiIpIcgwYREREREUmOQYOIiIiIiCTHoEFERERERJJj0CAiIiIiIskxaBARERERkeQYNJ4BMpkMP/74Y12XQUTPuDVr1sDV1RVyuRzLli3DnDlz0Lp167ouCwBw4cIFyGQyxMfHP/Z9ccwlIjIMg8YDunLlCiZNmgRPT0+YmZnBwcEB/v7+WLVqFUpLSx/rvu92Us/JycGrr776WPdNRHVrxIgRmDNnDoCaX3QvXLgAoPYv2DeXpVZUVIQPPvgAM2bMQFZWFsaOHYtp06bh119/lXxf9zNixAgEBQX97ft9GtwegqKjo+Hu7g5A/98QEdHfwaiuC3ianD9/Hv7+/rCxscGCBQvQsmVLmJqaIjExEWvWrIGzszMGDBhQa7uqqioYGxs/trocHR0fW99ERABw8eJFVFVVoW/fvnByctKtt7CwqMOqiIjoScYrGg9g/PjxMDIywh9//IE333wTPj4+8PDwwMCBAxEZGYn+/fsDqPlEadWqVRgwYABUKhW++OILAMDOnTvRtm1bmJmZwcPDA3PnzkV1dbWu/4KCAowZMwb29vawsrJCt27dkJCQAABYt24d5s6di4SEBMhkMshkMqxbt063v5ufYN38NHP79u3o2rUrlEolfH19cfToUb1j+fe//w1XV1colUq89tprCAsLg42NzeN9A4nob7du3TrY2Njg559/hre3N5RKJd544w2UlpYiIiIC7u7usLW1xYcffgiNRnPXPlq2bAkA8PDw0F1Ruf0q680rDV999RWcnJxQr149TJgwAVVVVbo2FRUVmDZtGpydnaFSqfDSSy8hOjra4OOZM2cOIiIisHPnTt1YeOv258+fv+vYl5eXh6FDh8LZ2RlKpRItW7bEpk2b9PoPCAjAhx9+iI8//hh2dnZwdHS871WA0NBQODk54dSpU7Veu3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iIiIiISHIMGkREREREJDkGDSIiIiIiktz/A0/x9tng3v+UAAAAAElFTkSuQmCC",
      "text/plain": [
       "<Figure size 1000x200 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33muser_proxy\u001b[0m (to chatbot):\n",
      "\n",
      "\u001b[32m***** Response from calling function \"python\" *****\u001b[0m\n",
      "(0.0, 1.0, 0.0, 1.0)\n",
      "\u001b[32m***************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mchatbot\u001b[0m (to user_proxy):\n",
      "\n",
      "TERMINATE\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    }
   ],
   "source": [
    "llm_config = {\n",
    "    \"functions\": [\n",
    "        {\n",
    "            \"name\": \"python\",\n",
    "            \"description\": \"run cell in ipython and return the execution result.\",\n",
    "            \"parameters\": {\n",
    "                \"type\": \"object\",\n",
    "                \"properties\": {\n",
    "                    \"cell\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"description\": \"Valid Python cell to execute.\",\n",
    "                    }\n",
    "                },\n",
    "                \"required\": [\"cell\"],\n",
    "            },\n",
    "        },\n",
    "        {\n",
    "            \"name\": \"sh\",\n",
    "            \"description\": \"run a shell script and return the execution result.\",\n",
    "            \"parameters\": {\n",
    "                \"type\": \"object\",\n",
    "                \"properties\": {\n",
    "                    \"script\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"description\": \"Valid shell script to execute.\",\n",
    "                    }\n",
    "                },\n",
    "                \"required\": [\"script\"],\n",
    "            },\n",
    "        },\n",
    "    ],\n",
    "    \"config_list\": config_list,\n",
    "    \"request_timeout\": 120,\n",
    "}\n",
    "chatbot = autogen.AssistantAgent(\n",
    "    name=\"chatbot\",\n",
    "    system_message=\"For coding tasks, only use the functions you have been provided with. Reply TERMINATE when the task is done.\",\n",
    "    llm_config=llm_config,\n",
    ")\n",
    "\n",
    "# create a UserProxyAgent instance named \"user_proxy\"\n",
    "user_proxy = autogen.UserProxyAgent(\n",
    "    name=\"user_proxy\",\n",
    "    is_termination_msg=lambda x: x.get(\"content\", \"\") and x.get(\"content\", \"\").rstrip().endswith(\"TERMINATE\"),\n",
    "    human_input_mode=\"NEVER\",\n",
    "    max_consecutive_auto_reply=10,\n",
    "    code_execution_config={\"work_dir\": \"coding\"},\n",
    ")\n",
    "\n",
    "# define functions according to the function desription\n",
    "from IPython import get_ipython\n",
    "\n",
    "def exec_python(cell):\n",
    "    ipython = get_ipython()\n",
    "    result = ipython.run_cell(cell)\n",
    "    log = str(result.result)\n",
    "    if result.error_before_exec is not None:\n",
    "        log += f\"\\n{result.error_before_exec}\"\n",
    "    if result.error_in_exec is not None:\n",
    "        log += f\"\\n{result.error_in_exec}\"\n",
    "    return log\n",
    "\n",
    "def exec_sh(script):\n",
    "    return user_proxy.execute_code_blocks([(\"sh\", script)])\n",
    "\n",
    "# register the functions\n",
    "user_proxy.register_function(\n",
    "    function_map={\n",
    "        \"python\": exec_python,\n",
    "        \"sh\": exec_sh,\n",
    "    }\n",
    ")\n",
    "\n",
    "# start the conversation\n",
    "user_proxy.initiate_chat(\n",
    "    chatbot,\n",
    "    message=\"Draw two agents chatting with each other with an example dialog. Don't add plt.show().\",\n",
    ")\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "e9531d55",
   "metadata": {},
   "source": [
    "## Another example with Wolfram Alpha API\n",
    "\n",
    "We give another example of querying Wolfram Alpha API to solve math problem. We use the predefined function `MathUserProxyAgent().execute_one_wolfram_query` as the function to be called."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "4a917492",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33muser_proxy\u001b[0m (to chatbot):\n",
      "\n",
      "Problem: Find all $x$ that satisfy the inequality $(2x+10)(x+3)<(3x+9)(x+8)$. Express your answer in interval notation.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mchatbot\u001b[0m (to user_proxy):\n",
      "\n",
      "\u001b[32m***** Suggested function Call: query_wolfram *****\u001b[0m\n",
      "Arguments: \n",
      "{\n",
      "  \"query\": \"solve (2x+10)(x+3)<(3x+9)(x+8) for x\"\n",
      "}\n",
      "\u001b[32m**************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[35m\n",
      ">>>>>>>> EXECUTING FUNCTION query_wolfram...\u001b[0m\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33muser_proxy\u001b[0m (to chatbot):\n",
      "\n",
      "\u001b[32m***** Response from calling function \"query_wolfram\" *****\u001b[0m\n",
      "('Assumption: solve (2 x + 10) (x + 3)<(3 x + 9) (x + 8) for x \\nAnswer: ans 0: x<-14\\nans 1: x>-3\\n', True)\n",
      "\u001b[32m**********************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mchatbot\u001b[0m (to user_proxy):\n",
      "\n",
      "The solution to the inequality $(2x+10)(x+3)<(3x+9)(x+8)$ is $x \\in (-\\infty, -14) \\cup (-3, +\\infty)$. TERMINATE\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33muser_proxy\u001b[0m (to chatbot):\n",
      "\n",
      "\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mchatbot\u001b[0m (to user_proxy):\n",
      "\n",
      "TERMINATE\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "from flaml.autogen.agentchat.contrib.math_user_proxy_agent import MathUserProxyAgent\n",
    "\n",
    "# you need to provide a wolfram alpha appid to run this example\n",
    "if not os.environ.get(\"WOLFRAM_ALPHA_APPID\"):\n",
    "    os.environ[\"WOLFRAM_ALPHA_APPID\"] = open(\"wolfram.txt\").read().strip()\n",
    "\n",
    "llm_config = {\n",
    "    \"model\": \"gpt-4-0613\",\n",
    "    \"functions\": [\n",
    "        {\n",
    "            \"name\": \"query_wolfram\",\n",
    "            \"description\": \"Return the API query result from the Wolfram Alpha. the ruturn is a tuple of (result, is_success).\",\n",
    "            \"parameters\": {\n",
    "                \"type\": \"object\",\n",
    "                \"properties\": {\n",
    "                    \"query\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"description\": \"The Wolfram Alpha code to be executed.\",\n",
    "                    }\n",
    "                },\n",
    "                \"required\": [\"query\"],\n",
    "            },\n",
    "        }\n",
    "    ],\n",
    "    \"config_list\": config_list,\n",
    "}\n",
    "chatbot = autogen.AssistantAgent(\n",
    "    name=\"chatbot\",\n",
    "    system_message=\"Only use the functions you have been provided with. Do not ask user to perform other actions than executing the functions. Reply TERMINATE when the task is done.\",\n",
    "    llm_config=llm_config,\n",
    ")\n",
    "\n",
    "# the key in `function_map` should match the function name in \"functions\" above\n",
    "# we register a class instance method directly\n",
    "user_proxy = autogen.UserProxyAgent(\n",
    "    \"user_proxy\",\n",
    "    max_consecutive_auto_reply=2,\n",
    "    human_input_mode=\"NEVER\",\n",
    "    function_map={\"query_wolfram\": MathUserProxyAgent().execute_one_wolfram_query},\n",
    ")\n",
    "\n",
    "# start the conversation\n",
    "user_proxy.initiate_chat(\n",
    "    chatbot,\n",
    "    message=\"Problem: Find all $x$ that satisfy the inequality $(2x+10)(x+3)<(3x+9)(x+8)$. Express your answer in interval notation.\",\n",
    ")\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "flaml_dev",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.17"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
